<template>
  <div class="liveSet">
    <div class="form-breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商家管理</el-breadcrumb-item>
        <el-breadcrumb-item>商品订单</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="table-bar">
      <div class="selectBox">
        订单状态：
        <el-select
          style="margin-right: 10px"
          clearable
          @change="selectOrderStatus"
          v-model="orderValue"
          placeholder="请选择"
        >
          <el-option
            v-for="item in orderStatus"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        卖场：
        <el-select
          v-model="marketId"
          style="margin-right: 10px"
          @change="selectMarket"
          filterable
          placeholder="请选择卖场"
        >
          <el-option
            v-for="item in marketList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
        订单日期：
        <el-date-picker
          clearable
          v-model="valueTime"
          :picker-options="pickerOptions"
          type="datetimerange"
          @change="selectTime"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
        <el-popover
          placement="bottom"
          width="310"
          @hide="hideFN"
          v-model="visible"
        >
          <div
            style="
              display: flex;
              align-items: center;
              justify-content: flex-end;
            "
          >
            从第几条开始导出：<el-input
              style="width: 50%"
              @blur="inputStartNo"
              v-model="start_no"
              placeholder="请输入"
              type="number"
            ></el-input>
          </div>
          <div
            style="
              display: flex;
              align-items: center;
              margin: 10px 0;
              justify-content: flex-end;
            "
          >
            导出数量(最大5000)：<el-input
              style="width: 50%"
              @blur="inputEndNo"
              v-model="end_no"
              placeholder="请输入"
              type="number"
            ></el-input>
          </div>
          <div style="text-align: right; margin: 0">
            <el-button size="mini" type="text" @click="visible = false"
              >取消</el-button
            >
            <el-button type="primary" size="mini" @click="outFile"
              >确定</el-button
            >
          </div>
          <el-button
            slot="reference"
            style="margin-left: 20px"
            type="primary"
            size="medium"
            >导出</el-button
          >
        </el-popover>
        <!-- <el-button type="primary" style="margin-left:10px;" size="medium" @click="outFile">导出</el-button> -->
      </div>
      <div class="inputSearch">
        <el-input
          placeholder="输入订单号模糊搜索"
          v-model="orderKeyword"
          clearable
          @input="clearInputOrder"
          @keyup.enter.native="searchInputOrder"
        ></el-input>
        <el-input
          style="margin-left: 10px"
          placeholder="商家，用户昵称手机号关键字筛选"
          v-model="keyword"
          clearable
          @input="clearInput"
          @keyup.enter.native="searchInput"
        ></el-input>
        <el-button type="primary" size="medium" @click="searchInput"
          >搜索</el-button
        >
      </div>
    </div>
    <div class="partnerList_table">
      <div class="partnerList_bottom_table">
        <table>
          <tr>
            <th></th>
            <th>序号</th>
			<th>订单类型</th>
            <th>订单号</th>
            <th>店铺名称（id）</th>
            <th>购买用户（id）</th>
            <th>销售价格</th>
            <th>成本价格</th>
            <th>原价格</th>
            <th>下单数量</th>
            <th>是否多次支付</th>
            <th>支付金额</th>
            <th>下单时间</th>
            <th>支付时间</th>
			<th>拼团状态</th>
            <th>订单状态</th>
            <th>操作</th>
          </tr>
          <tr v-for="(v, i) in tableList" :key="i">
            <td>
              <font
                class="checkbox"
                v-if="v.order_status == 1"
                :class="{ check_active: v.checked }"
                @click="handlerCheckbox(i, v.checked)"
                ><i class="el-icon-check"></i
              ></font>
            </td>
            <td>{{ i + 1 + (page - 1) * pageSize }}</td>
			<td>{{v.buy_type==0?'普通商品':v.buy_type=='1'?'秒杀商品':'拼团商品'}}</td> 
            <td>
              <p>主订单：{{ v.order_id }}</p>
              <p>子订单：{{ v.order_code }}</p>
            </td>
            <td>
              {{ v.store_name }}（{{ v.store_id }}）
              <p>{{ v.store_mobile }}</p>
            </td>
            <td>
              {{ v.nickname }}（{{ v.user_id }}）
              <p>{{ v.mobile }}</p>
            </td>
            <td>{{ v.price }}</td>
            <td>{{ v.cost_price }}</td>
            <td>{{ v.primary_price }}</td>
            <td>{{ v.num }}</td>
            <td>{{ v.is_many_way == 0 ? "否" : "是" }}</td>
            <td>{{ v.pay_price }}</td>
            <td>
              {{ $moment(v.create_time * 1000).format("yyyy-MM-DD HH:mm:ss") }}
            </td>
            <td>
              {{
                v.pay_time
                  ? $moment(v.pay_time * 1000).format("yyyy-MM-DD HH:mm:ss")
                  : ""
              }}
            </td>
			<td>
				{{v.pintuan_status==1?'拼团中':v.pintuan_status==2?'拼团成功':v.pintuan_status==3?'拼团失败':'非拼团商品'}}
			</td>
            <td>
              {{
                v.order_status == 1
                  ? "待付款"
                  : v.order_status == 2
                  ? "待发货"
                  : v.order_status == 3
                  ? "待收货"
                  : v.order_status == 4
                  ? "已完成"
                  : v.order_status == 5
                  ? "已关闭"
                  : ""
              }}
            </td>
            <td>
              <el-button
                type="primary"
                @click="toOrderDetail(v.order_code, v.user_id)"
                >详情</el-button
              >
              <template v-if="v.order_status == 1">
                <el-popconfirm title="确定关闭该订单吗？" @confirm="closeOrderTd(v.order_id)"> 
                  <el-button
                    slot="reference"
                    type="danger"
                    style="margin: 0 10px"
                    size="mini"
                    >关闭</el-button>
                </el-popconfirm>
              </template>
              <!-- <el-popover title="确定关闭所选订单吗？" @hide="hideFn" trigger="manual" v-model="v.showPopTd">
                超时：
                <el-select v-model="closeTime" clearable placeholder="请选择">
                  <el-option
                    v-for="item in closeTimeList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
                <p style="text-align:right;margin:20px 0 0 0;">
                    <el-button size="mini" @click="v.showPopTd = false">取消</el-button>
                    <el-button type="primary" size="mini" @click="closeOrderTd(v.order_id)">确定</el-button>
                </p>
                <el-button v-if="v.order_status == 1" slot="reference" style="margin: 0 10px" type="danger" size="mini" @click="v.showPopTd = !v.showPopTd">关闭</el-button>
              </el-popover> -->
              <el-button
                v-if="v.order_status == 3"
                type="warning"
                @click="toReceiv(v.order_code, v.user_id, v.id)"
                >确认收货</el-button
              >
            </td>
          </tr>
          <tr v-if="tableList.length == 0">
            <td class="table_title" colspan="20">当前数据空空如也</td>
          </tr>
        </table>
        <div class="partnerList_bottom_page">
          <div class="partnerList_bottom_page_left">
            <div
              class="partnerList_bottom_page_left_checkAll"
              @click="handerCheckAll"
            >
              <font class="checkbox" :class="{ check_active: checkAll }"
                ><i class="el-icon-check"></i
              ></font>
            </div>
            全选
            <el-popconfirm title="确定关闭该订单吗？" @confirm="closeOrderAll">
              <el-button
                slot="reference"
                type="danger"
                style="margin-left:20px;"
                size="mini"
                :disabled="!orderIdChecked.length"
                >关闭</el-button
              >
            </el-popconfirm>
            <!-- <el-popover title="确定关闭所选订单吗？" @hide="hideFn" trigger="manual" v-model="showPopAll">
              超时：
              <el-select v-model="closeTime" clearable placeholder="请选择">
                <el-option
                  v-for="item in closeTimeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
             <p style="text-align:right;margin:20px 0 0 0;">
                <el-button size="mini" @click="showPopAll = false">取消</el-button>
                <el-button type="primary" size="mini" @click="closeOrderAll">确定</el-button>
             </p>
              <el-button slot="reference" :disabled="!orderIdChecked.length" style="margin-left:20px;" type="danger" size="mini" @click="showPopAll = !showPopAll">关闭</el-button>
            </el-popover> -->

          </div>
          <div class="partnerList_bottom_page_right">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="page"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              background
            >
            </el-pagination>
          </div>
        </div>
      </div>
    </div>

    <!-- 订单详情弹框 -->
    <el-dialog
      title="订单详情"
      :visible.sync="dialogVisibleInfo"
      width="40%"
      @close="closeOrderDetailFn"
    >
      <div class="orderDetailBox">
        <div class="item">
          <span>订单号：</span>
          <div id="content">{{ orderData.order_code }}</div>
          <font
            class="copyConsignee"
            data-clipboard-target="#content"
            @click="copyText"
            >复制</font
          >
        </div>
        <div class="item">
          <span>定金金额：</span>{{ orderData.deposit_price }}
        </div>
        <div class="item">
          <span>已支付金额：</span>{{ orderData.pay_price }}
        </div>
        <div class="item"><span>订单金额：</span>{{ orderData.price }}</div>
        <div class="item">
          <span>订单状态：</span
          >{{
            orderData.order_status == 1
              ? "待付款"
              : orderData.order_status == 2
              ? "待发货"
              : orderData.order_status == 3
              ? "待收货"
              : orderData.order_status == 4
              ? "已完成"
              : orderData.order_status == 5
              ? "已关闭"
              : ""
          }}
        </div>
		<div class="item" v-if="orderData.buy_type==2"><span>拼团状态：</span>{{groupStatus[orderData.pintuan_status] }}</div>
        <div class="item"><span>收货人：</span>{{ orderData.name }}</div>
        <div class="item">
          <span>收货地址：</span>{{ orderData.province }} {{ orderData.city }}
          {{ orderData.area }} {{ orderData.address }}
        </div>
        <div class="item"><span>手机号：</span>{{ orderData.mobile }}</div>
        <div class="item">
          <span>配送方式：</span
          >{{
            orderData.move_way == 1
              ? "快递"
              : orderData.move_way == 2
              ? "自提"
              : ""
          }}
        </div>
        <div class="item">
          <span>创建时间：</span
          >{{
            $moment(orderData.create_time * 1000).format("yyyy-MM-DD HH:mm:ss")
          }}
        </div>
        <div class="item">
          <span>商品信息：</span>
          <el-table
            :data="orderData.list"
            border
            max-height="400px"
            style="width: 100%"
          >
            <el-table-column prop="product_title" label="商品标题" width="180">
            </el-table-column>
            <el-table-column prop="main_imgurl" label="商品主图">
              <template slot-scope="scope">
                <img
                  style="width: 50px; height: 50px"
                  :src="scope.row.main_imgurl"
                  alt=""
                />
              </template>
            </el-table-column>
            <el-table-column prop="price" label="价格" width="180">
            </el-table-column>
            <el-table-column prop="num" label="数量"> </el-table-column>
          </el-table>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleInfo = false">取 消</el-button>
        <!-- <el-button type="primary" @click="dialogVisibleInfo = false">确 定</el-button> -->
      </span>
    </el-dialog>
  </div>
</template>
<script>
import ClipboardJS from "clipboard";
export default {
  data() {
    return {
      checkAll: false,
      page: 1,
      pageSize: 10,
      total: 0,
      checkBoxAll: [], // 选中的数据
      shelvesAlls: [],
      tableList: [],
      keyword: "",
      orderKeyword: "",
      code: "",
      activity_id: "", //主活动id
      fatherName: "", //主活动名称

      orderStatus: [
        {
          label: "待付款",
          value: 1,
        },
        {
          label: "待发货",
          value: 2,
        },
        {
          label: "待收货",
          value: 3,
        },
        {
          label: "已完成",
          value: 4,
        },
        {
          label: "已关闭",
          value: 5,
        },
      ],
      orderValue: "",

      dialogVisible: false,

      dialogVisibleInfo: false,
      orderData: {},
      marketId: 1, //卖场id
      marketList: [],
      valueTime: [],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
        selectableRange: "00:00:00 - 23:59:59"
      },
      startDate: "",
      endDate: "",

      // 导出弹出框
      visible: false,
      start_no: 1, //从第几条开始导出
      end_no: 1, //导出数量
      orderIdChecked:[], //选择的订单id]
      // 关闭时间
      closeTimeList:[{
        value:'',
        label:'不限时间'
      },{
        value:15,
        label:'15分钟'
      },{
        value:30,
        label:'30分钟'
      },{
        value:60,
        label:'60分钟'
      },{
        value:1440,
        label:'1440分钟（1天）'
      }],
      closeTime:'',
      showPopAll:false,
	  groupStatus:{
		  1:'拼团中',
		  2:'拼团成功',
		  3:'拼团失败'
	  }
    };
  },
  mounted() {
    console.log(Date.now());
    this.activity_id = this.$route.query.id;
    this.fatherName = this.$route.query.name;
    this.getSetList();
    this.remoteMethod();
  },
  methods: {
    // 获取卖场列表
    remoteMethod() {
      this.$http.post("/api/root/Market/marketList").then((res) => {
        if (res.code == 1) {
          this.marketList = res.data ? res.data : [];
        }
      });
    },
    // 选择卖场
    selectMarket() {
      this.page = 1;
      this.pageSize = 10;
      this.orderIdChecked = []
      this.checkAll = false
      this.getSetList();
    },
    // 获取活动商品订单列表o
    getSetList() {
      let params = {
        keyword: this.keyword,
        page: this.page,
        pagesize: this.pageSize,
        order_no: this.orderKeyword,
        order_status: this.orderValue,
        market_id: this.marketId,
        start_at: this.startDate,
        end_at: this.endDate,
      };
      this.$http.post("/api/root/store/orders", params).then((res) => {
        console.log(res, "活动列表");
        if (res.code == 1) {
          res.data.data.map((item) => {
            item.checked = false;
            item.showPopTd = false
          });
          this.tableList = res.data.data ? res.data.data : [];
          this.total = res.data.count;
        }
      });
    },

    // 选择时间
    selectTime() {
      this.startDate = this.valueTime
        ? this.$moment(this.valueTime[0]).format("yyyy-MM-DD HH:mm:ss")
        : "";
      this.endDate = this.valueTime
        ? this.$moment(this.valueTime[1]).format("yyyy-MM-DD HH:mm:ss")
        : "";
      this.page = 1;
      this.pageSize = 10;
      this.orderIdChecked = []
      this.checkAll = false
      this.getSetList();
    },

    // 输入验证
    inputStartNo() {
      if (this.start_no * 1 < 1) {
        this.start_no = 1;
        this.$message.warning("最小为第1条开始导出");
      } else if (this.start_no * 1 > this.total * 1) {
        this.start_no = this.total;
        this.$message.warning(`最大为第${this.total}条开始导出`);
      }
    },
    inputEndNo() {
      if (this.end_no * 1 < 1) {
        this.end_no = 1;
        this.$message.warning("最小导出数量为1");
      } else if (this.end_no * 1 > 5000) {
        this.end_no = 5000;
        this.$message.warning("最大导出数量为5000");
      }
    },

    // 导出弹出隐藏
    hideFN() {
      this.start_no = 1;
      this.end_no = 1;
    },

    // 导出
    outFile() {
      var a = document.createElement("a");
      a.setAttribute(
        "href",
        `/api/root/order/ordinary/export?keyword=${this.keyword}&order_no=${this.orderKeyword}&order_status=${this.orderValue}&market_id=${this.marketId}&start_at=${this.startDate}&end_at=${this.endDate}&start_no=${this.start_no}&end_no=${this.end_no}`
      );
      a.setAttribute("target", "_blank");
      a.setAttribute("id", "startTelMedicine");
      // 防止反复添加
      if (document.getElementById("startTelMedicine")) {
        document.body.removeChild(document.getElementById("startTelMedicine"));
      }
      document.body.appendChild(a);
      a.click();
    },

    // 复制
    copyText() {
      let that = this;
      let clipboard = new ClipboardJS(".copyConsignee");
      clipboard.on("success", function (e) {
        e.clearSelection();
        that.$message.success("复制成功");
        clipboard.destroy();
      });
      clipboard.on("error", function (e) {
        console.log(e);
        that.$message.warning("复制失败，请重试");
        clipboard.destroy();
      });
    },

    // 进入详情
    toDetail(orderId) {
      this.$router.push({
        name: "activityGoodsOrderDetail",
        query: { orderId },
      });
    },

    // 选择订单状态
    selectOrderStatus() {
      this.page = 1;
      this.pagesize = 10;
      this.orderIdChecked = []
      this.checkAll = false
      this.getSetList();
    },

    // 节目列表
    toParty(id) {
      this.$router.push({ name: "partyList", query: { id } });
    },

    // 搜索
    searchInput() {
      this.page = 1;
      this.pagesize = 10;
      this.orderIdChecked = []
      this.checkAll = false
      this.getSetList();
    },
    // 清空输入框
    clearInput() {
      this.page = 1;
      this.pagesize = 10;
      if (this.keyword == "") {
        this.orderIdChecked = []
        this.checkAll = false
        this.getSetList();
      }
    },

    searchInputOrder() {
      this.page = 1;
      this.pagesize = 10;
      if (this.orderKeyword != "") {
        this.orderIdChecked = []
        this.checkAll = false
        this.getSetList();
      }
    },
    // 清空输入框
    clearInputOrder() {
      this.page = 1;
      this.pagesize = 10;
      if (this.orderKeyword == "") {
        this.orderIdChecked = []
        this.checkAll = false
        this.getSetList();
      }
    },

    // 补发奖品
    toBuFa(order_id) {
      this.$http
        .post("/api/root/activity/order/sent", { order_id })
        .then((res) => {
          console.log(res, "补发奖品结果");
          if (res.code == 1) {
            this.$message.success("补发成功");
            this.getSetList();
          } else {
            this.$message.warning(res.msg);
          }
        });
    },

    // 删除按钮
    toDel(id) {
      this.$confirm("此操作将删除此该活动, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$http.post("/api/root/activity/son/del", { id }).then((res) => {
          console.log(res);
          if (res.code == 1) {
            this.getSetList();
            this.$message({
              type: "success",
              message: "删除成功",
            });
          } else {
            this.$message.warning(res.msg);
          }
        });
      });
    },

    // 编辑按钮
    toEdit(id) {
      this.$router.push({
        name: "addChildActivity",
        query: { id, activity_id: this.activity_id },
      });
    },

    // 更改状态
    toChange(id, sta) {
      let params = {
        id,
        status: sta == 1 ? 0 : 1,
      };
      this.$http.post("/api/root/activity/son/status", params).then((res) => {
        console.log(res, "更改状态");
        if (res.code == 1) {
          this.$message.success("更改成功");
          this.getSetList();
        } else {
          this.$message.warning(res.msg);
        }
      });
    },

    // 订单详情按钮
    toOrderDetail(order_code, buy_user_id) {
      this.dialogVisibleInfo = true;
      this.$http
        .post("/api/root/store/order/detail", { order_code, buy_user_id })
        .then((res) => {
          console.log(res, "订单详情");
          if (res.code == 1) {
            this.orderData = res.data;
          }
        });
    },
    // 关闭订单详情对话框
    closeOrderDetailFn() {
      this.orderData = {};
    },

    // 订单确认收货
    toReceiv(orderId, userId, id) {
      this.$confirm("是否确认收货", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let params = {
            buy_user_id: userId,
            id_lst: id,
            order_id: orderId,
          };
          this.$http
            .post("/api/root/store/order/confirm", params)
            .then((res) => {
              console.log(res, "确认收货结果");
              if (res.code == 1) {
                this.$message.success("操作成功");
                this.getSetList();
              } else {
                this.$message.warning(res.msg);
              }
            });
        })
        .catch(() => {});
    },


    // 多选
    handlerCheckbox(i, checked) {
      console.log(i, checked, "-----");
      if (this.tableList[i].checked) {
        this.tableList[i].checked = false;
      } else {
        this.tableList[i].checked = true;
      }
      let arr = [];
      this.tableList.map((item) => {
        if (item.order_status == 1) {
          arr.push(item);
        }
      });
      // console.log(arr,'..');
      this.checkAll = arr.every((item) => item.checked == true);
      // console.log(this.checkAll, "9999");

      let orderIdArr = [] //获取选择的订单id
      this.tableList.map(item=>{
        if(item.checked){
          orderIdArr.push(item.order_id)
        }
      })
      this.orderIdChecked = orderIdArr
      console.log(this.orderIdChecked,'已选择的');
    },
    // 全选与全不选
    handerCheckAll() {
      this.checkAll = !this.checkAll;
      this.tableList.map((item) => {
        if (item.order_status == 1) {
          item.checked = this.checkAll;
        }
      });

      let orderIdArr = []  //获取选择的订单id
      this.tableList.map(item=>{
        if(item.checked){
          orderIdArr.push(item.order_id)
        }
      })
      this.orderIdChecked = orderIdArr
      console.log(this.orderIdChecked,'已选择的');
    },

    // 单个关闭弹出确定按钮
    closeOrderTd(orderId){
      // this.$confirm('确定关闭该订单吗？',{
      //   confirmButtonText:'确定',
      //   cancelButtonText:'取消',
      //   type:'warning'
      // }).then(()=>{
        this.closeOrderFn(orderId)
      // }).catch(()=>{})
    },

    // 全选后关闭订单按钮
    closeOrderAll(){
      let orderId = this.orderIdChecked.join(',')
      this.closeOrderFn(orderId)
    },

    // 关闭订单操作
    closeOrderFn(orderId){
      let params = {
        order_type:0,
        order_id:orderId,
        time:this.closeTime,
        market_id:this.marketId
      }
      this.$http.post('/api/root/store/order/close',params).then(res=>{
        if(res.code==1){
          this.$message.success('关闭成功');
          this.showPopAll = false
          this.orderIdChecked = []
          this.getSetList()
        }else{
          this.$message.warning(res.msg)
        }
      })
    },

    // 弹出框关闭
    hideFn(){
      this.closeTime = ''
    },

    delBtn(e){
      e.stopPropagation();
    },

    handleSizeChange(val) {
      this.page = 1
      this.pageSize = val;
      this.getSetList();
      this.checkBoxAll = [];
      this.shelvesAlls = [];
      this.orderIdChecked = [];
      this.checkAll = false;
    },
    handleCurrentChange(val) {
      this.page = val;
      this.getSetList();
      this.checkBoxAll = [];
      this.shelvesAlls = [];
      this.orderIdChecked = [];
      this.checkAll = false;
    },
  },
};
</script>
<style lang="less" scoped>
@import "index.less";
</style>